﻿package com.agileai.miscdp.hotweb.generator.standard;

import java.io.File;

import org.dom4j.Document;
import org.dom4j.io.SAXReader;

import com.agileai.miscdp.NoOpEntityResolver;
import com.agileai.miscdp.hotweb.domain.ResFileValueProvider;
import com.agileai.miscdp.hotweb.domain.standard.StandardFuncModel;
import com.agileai.miscdp.hotweb.generator.Generator;
import com.agileai.miscdp.util.MiscdpUtil;
import com.agileai.util.XmlUtil;
/**
 * Handler配置代码生成器
 */
public class SMHandlerCfgGenerator implements Generator{
	private StandardFuncModel funcModel = null;
	private String configFile = null;
	private String encoding = "UTF-8";
	
	public void generate() {
		try {
	        SAXReader saxReader = new SAXReader();
	        saxReader.setEntityResolver(new NoOpEntityResolver());
	        saxReader.setIncludeExternalDTDDeclarations(false);
	        saxReader.setValidation(false);
	        Document document = saxReader.read(new File(configFile));
	        
	        String listHandlerId = funcModel.getListHandlerId();
	        String listHandlerClass = funcModel.getListHandlerClass();
	        String listJspPage = funcModel.getListJspName();
	        MiscdpUtil.newHandlerConfigElement(document, listHandlerId, listHandlerClass, listJspPage);

	        String editHandlerId = funcModel.getEditHandlerId();
	        String editHandlerClass = funcModel.getEditHandlerClass();
	        String editJspPage = funcModel.getDetailJspName();
	        MiscdpUtil.newHandlerConfigElement(document, editHandlerId, editHandlerClass, editJspPage);
	        
	        ResFileValueProvider resFileValueProvider = funcModel.getResFileValueProvider();
	        if (resFileValueProvider != null){
	        	String tableName = funcModel.getTableName();
	        	String prefixName = MiscdpUtil.getValidName(tableName);
	        	
	        	String resFileHandlerId = prefixName+"ResouceUploader";
		        String resFileHandlerClass = MiscdpUtil.parsePackage(funcModel.getEditHandlerClass())+"."+resFileHandlerId+"Handler";
		        String resFileJspPage = MiscdpUtil.parseJspPath(funcModel.getDetailJspName())+"/"+resFileHandlerId+".jsp";
		        MiscdpUtil.newHandlerConfigElement(document, resFileHandlerId, resFileHandlerClass, resFileJspPage);
	        }
	        XmlUtil.writeDocument(document, encoding, configFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setConfigFile(String configFile) {
		this.configFile = configFile;
	}

	public void setFuncModel(StandardFuncModel funcModel) {
		this.funcModel = funcModel;
	}
}
